package com.ayit.klog.utils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/***
 *
 * @Author lny
 * @CreateTime 2024年08月11日 13:36:09
 * @Description
 */
public class ZipUtils {
    
    public static boolean zipFile(String sourceFilePath, String zipFilePath) {
        File sourceFile = new File(sourceFilePath);
        long startTime = System.currentTimeMillis();
        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
                ZipOutputStream zos = new ZipOutputStream(fos)) {
            zipFile(sourceFile, sourceFile.getName(), zos);
        }catch (Exception e){
            return false;
        }finally {
            long dis = System.currentTimeMillis() - startTime;
            Log.d("KLog","zip: "+sourceFilePath+">>>>>"+zipFilePath +",time="+dis);
        }
        return true;
    }
    
    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zos) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith("/")) {
                zos.putNextEntry(new ZipEntry(fileName));
            } else {
                zos.putNextEntry(new ZipEntry(fileName + "/"));
            }
            zos.closeEntry();
            File[] children = fileToZip.listFiles();
            for (File childFile : children) {
                zipFile(childFile, fileName + "/" + childFile.getName(), zos);
            }
            return;
        }
        try (FileInputStream fis = new FileInputStream(fileToZip)) {
            ZipEntry zipEntry = new ZipEntry(fileName);
            zos.putNextEntry(zipEntry);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) >= 0) {
                zos.write(buffer, 0, length);
            }
        }
    }
}
